#!/usr/bin/env bash

# 当使用未初始化的变量时，程序自动退出
# 也可以使用命令 set -o nounset
set -u

# 当任何一行命令执行失败时，自动退出脚本
# 也可以使用命令 set -o errexit
set -e

set -x

namespace=dabai-fat
param1="$1"
param2="$2"

while [ -n "${param1}" ]
do
  case "${param1}" in
    -n)
        namespace="${param2:-dabai-fat}"
        ;;
  esac
  break
done

CURRENT_TIME=`date '+%Y%m%d%H%M'`

CURRENT_HOUR_DIR=`date '+%Y%m%d%H'`

if [[ ! -e ${CURRENT_HOUR_DIR} ]]; then
    mkdir ${CURRENT_HOUR_DIR}
elif [[ ! -d ${CURRENT_HOUR_DIR} ]]; then
    echo "${CURRENT_HOUR_DIR} already exists but is not a directory" 1>&2
fi

declare -A map=(
    ["deployment"]="deployment" 
    ["svc"]="svc"
    ["statefulset"]="statefulset"
    ["configmap"]="configmap"
    ["daemonset"]="daemonset"
    ["cronjob"]="cronjob"
    ["ingress"]="ingress"
    ["secret"]="secret"
    ["pvc"]="pvc"
    ["pv"]="pv"
)

for key in ${!map[@]}
do
  kubectl get ${key} -n ${namespace} \
  -o yaml > ./${CURRENT_HOUR_DIR}/kubernetes-${namespace}-${key}-${CURRENT_TIME}.yaml
done